package com.feituan.core.pojo.response;

import com.feituan.core.constants.Constant;
import com.feituan.core.error.SystemCode;
import com.feituan.core.exception.SystemException;
import lombok.Data;
import lombok.experimental.Accessors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;

import java.util.Objects;

@Data
@Accessors(chain = true)
public class Response<T> extends BaseResponse<T> {
    private static final Logger LOGGER = LoggerFactory.getLogger(Response.class);

    public static <T> Response<T> success(T data) {
        return build(SystemCode.SUCCESS, data, null);
    }

    public static <T> Response<T> success(T data, String msg) {
        return build(SystemCode.SUCCESS, data, msg);
    }

    public static <T> Response<T> success() {
        return success(null);
    }


    public static <T> Response<T> failed(SystemCode systemCode) {
        return failed(systemCode, null);
    }


    public static <T> Response<T> failed(SystemCode systemCode, String message) {
        return build(systemCode, null, message);
    }

    private static <T> Response<T> build(SystemCode systemCode, T data, String message) {
        if (Objects.isNull(systemCode)) {
            throw new SystemException(SystemCode.ILLEGAL_PARAM);
        }
        Response<T> response = new Response<T>();
        response.setData(data);
        if (systemCode.getCode() == 0) {
            response.setCode(Constant.RESPONSE_SUCCESS_CODE);
        } else {
            response.setCode(String.valueOf(systemCode.getCode()));
        }
        if (!ObjectUtils.isEmpty(message)) {
            response.setMsg(message);
        } else {
            response.setMsg(systemCode.getMessage());
        }
        return response;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public void setMsg(String msg) {
        this.errorMsg = msg;
    }

    public void setData(T data) {
        this.data = data;
    }

}
